package com.downbox.config;

import com.downbox.security.AuthInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * Web配置类
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private AuthInterceptor authInterceptor;

    @Value("${cors.allowed-origins:*}")
    private String allowedOrigins;

    @Value("${cors.allowed-methods:GET,POST,PUT,DELETE,OPTIONS}")
    private String allowedMethods;

    @Value("${cors.allowed-headers:*}")
    private String allowedHeaders;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 配置认证拦截器，拦截所有API请求
        registry.addInterceptor(authInterceptor)
                .addPathPatterns("/user/**", "/draw/**", "/history/**", "/submit/**", "/contribution/**")
                .excludePathPatterns(
                        "/mood/options", 
                        "/error", 
                        "/swagger-ui/**", 
                        "/swagger-ui.html",
                        "/api-docs/**",
                        "/v3/api-docs/**",
                        "/springdoc/**",
                        "/favicon.ico"
                );
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 配置CORS - 使用allowedOriginPatterns替代allowedOrigins以支持通配符并启用credentials
        registry.addMapping("/**")
                .allowedOriginPatterns(allowedOrigins.equals("*") ? new String[]{"**"} : allowedOrigins.split(","))
                .allowedMethods(allowedMethods.split(","))
                .allowedHeaders(allowedHeaders.split(","))
                .allowCredentials(true)
                .maxAge(3600);
    }
}